<template>
  <div class="wrapper">
    <el-form :model="ruleForm2" :label-position="labelPosition" :rules="rules2" ref="ruleForm2" label-width="60px" class="ruleForm">
      <h1>明理苑后台管理系统</h1>
      <el-form-item label="用户名" prop="username">
        <el-input v-model.number="ruleForm2.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="ruleForm2.password" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="loading" @click="submitForm('ruleForm2')">登陆</el-button>
        <el-button @click="resetForm('ruleForm2')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { mapGetters, mapActions } from 'vuex'
  export default {
    name: 'login',
    data () {
      var checkAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('用户名不能为空'))
        } else {
          callback()
        }
      }
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }
      return {
        labelPosition: 'right',
        ruleForm2: {
          password: '',
          username: ''
        },
        loading: false,
        rules2: {
          password: [
              { validator: validatePass, trigger: 'blur' }
          ],
          username: [
              { validator: checkAge, trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters([
        'loginError'
      ])
    },
    watch: {
      loginError (val) {
        console.log(val)
        this.$message.error(val[val.length - 1].message)
        this.loading = false
      }
    },
    methods: {
      ...mapActions([
        'login'
      ]),
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.login({...this.ruleForm2})
            this.loading = true
          } else {
            this.$message('不能提交，好好检查一下')
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style lang="stylus" scoped>
  h1
    text-align: center
    margin-bottom: 10px
  .ruleForm
    border: 1px solid #eee
    width: 500px
    margin: auto
    padding: 20px
    position: absolute
    top: 50%
    left: 50%
    transform: translate(-50%, -50%)
</style>
